package com.njtoyo.taxi.admin.service.local_service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.mapper.master.entity.Driver;
import com.njtoyo.taxi.admin.mapper.master.entity.User;
import com.njtoyo.taxi.admin.mapper.master.entity.local_service.*;
import com.njtoyo.taxi.admin.mapper.master.enums.local_service.LifeMemberCategory;
import com.njtoyo.taxi.admin.mapper.master.enums.local_service.LifeMemberPickupInfoState;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.UserMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.local_service.*;
import com.njtoyo.taxi.admin.rest.presenter.local_service.OrderDetailsPresenter;
import com.njtoyo.taxi.admin.rest.presenter.local_service.OrderPagePresenter;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.order.OrderPageWrapper;
import com.njtoyo.taxi.admin.service.local_service.LifeOrderService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static cn.hutool.core.bean.BeanUtil.copyProperties;
import static cn.hutool.core.util.ObjectUtil.isNotEmpty;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.springframework.util.ObjectUtils.isEmpty;

@Service
public class LifeOrderServiceImpl implements LifeOrderService {

    @Autowired
    private LifeMerchantMemberOrderMapper orderMapper;

    @Autowired
    private LifeMerchantMapper lifeMerchantMapper;

    @Autowired
    private LifeMerchantCommodityMapper lifeMerchantCommodityMapper;

    @Autowired
    private LifeMerchantCommodityCategoryMapper lifeMerchantCommodityCategoryMapper;

    @Autowired
    private LifeMemberMapper lifeMemberMapper;

    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LifeMemberPickupInfoMapper lifeMemberPickupInfoMapper;


    /**
     * 订单列表
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult<Page<OrderPagePresenter>> getPage(AdminUser adminUser, OrderPageWrapper wrapper) {
        switch (adminUser.getAccountType()) {
            case platform:
                break;
            default:
                return RestResult.failed("账号权限不够");
        }
        Page<OrderPagePresenter> page = orderMapper.getPage(wrapper);
        List<OrderPagePresenter> list = page.getRecords();
        if (isNotEmpty(list)) {
            //订单ids
            List<Long> ids = list.stream().map(OrderPagePresenter::getId)
                    .collect(toList());
            List<Long> merchantIds = list.stream().map(OrderPagePresenter::getMerchantId)
                    .collect(toList());
            List<Long> merchantCommodityIds = list.stream().map(OrderPagePresenter::getMerchantCommodityId)
                    .collect(toList());
            List<Long> memberIds = list.stream().map(OrderPagePresenter::getMemberId)
                    .collect(toList());
            //订单ID查核销时间
            QueryWrapper<LifeMemberPickupInfo> pickupInfoWrapper = new QueryWrapper<>();
            pickupInfoWrapper.in("ref_id", ids);
            List<LifeMemberPickupInfo> lifeMemberPickupInfos = lifeMemberPickupInfoMapper.selectList(pickupInfoWrapper);

            //商户名
            QueryWrapper<LifeMerchant> lifeMerchantWrapper = new QueryWrapper<>();
            lifeMerchantWrapper.select("id", "name");
            lifeMerchantWrapper.in("id", merchantIds);
            List<Map<String, Object>> maps = lifeMerchantMapper.selectMaps(lifeMerchantWrapper);
            Map<Long, String> map = maps.stream().collect(toMap(i -> Long.valueOf(i.get("id").toString()), i -> i.get("name").toString()));

            //商品名
            QueryWrapper<LifeMerchantCommodity> commodityQueryWrapper = new QueryWrapper<>();
            commodityQueryWrapper.select("id", "name");
            commodityQueryWrapper.in("id", merchantCommodityIds);
            List<Map<String, Object>> maps1 = lifeMerchantCommodityMapper.selectMaps(commodityQueryWrapper);
            Map<Long, String> map1 = maps1.stream().collect(toMap(i -> Long.valueOf(i.get("id").toString()), i -> i.get("name").toString()));

            //会员信息的用户id
            QueryWrapper<LifeMember> memberQueryWrapper = new QueryWrapper<>();
            memberQueryWrapper.select("id", "ref_id", "category");
            memberQueryWrapper.in("id", memberIds);
            List<LifeMember> memberList = lifeMemberMapper.selectList(memberQueryWrapper);
            //通过分类区分用户司机
            List<Long> userIds = memberList.stream().filter(member -> LifeMemberCategory.customer.equals(member.getCategory())).map(LifeMember::getRefId).collect(toList());
            List<Long> driverIds = memberList.stream().filter(member -> LifeMemberCategory.driver.equals(member.getCategory())).map(LifeMember::getRefId).collect(toList());

            //司机
            List<Driver> driverList = new ArrayList<>();
            if (isNotEmpty(driverIds)) {
                QueryWrapper<Driver> driverQueryWrapper = new QueryWrapper<>();
                driverQueryWrapper.select("id", "name", "mobile_number");
                driverQueryWrapper.in("id", driverIds);
                driverList = driverMapper.selectList(driverQueryWrapper);
            }
            //用户
            List<User> userList = new ArrayList<>();
            if (isNotEmpty(userIds)) {
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.select("id", "name", "mobile_number");
                userQueryWrapper.in("id", userIds);
                userList = userMapper.selectList(userQueryWrapper);
            }

            for (OrderPagePresenter commodityPagePresenter : list) {
                Long id = commodityPagePresenter.getId();
                commodityPagePresenter.setMerchantName(map.getOrDefault(commodityPagePresenter.getMerchantId(), null));
                commodityPagePresenter.setMerchantCommodityName(map1.getOrDefault(commodityPagePresenter.getMerchantCommodityId(), null));
                //核销信息
                lifeMemberPickupInfos.stream().filter(lifeMemberPickupInfo ->
                        lifeMemberPickupInfo.getRefId().equals(id)).forEach(lifeMemberPickupInfo -> {
                    commodityPagePresenter.setPickupInfo(lifeMemberPickupInfo);
                    //核销状态
                    if (isNotEmpty(lifeMemberPickupInfo)) {
                        //最晚提货时间
                        Integer pickupEndTimestamp = lifeMemberPickupInfo.getPickupEndTimestamp();
                        LifeMemberPickupInfoState state = lifeMemberPickupInfo.getState();
                        long time = new Date().getTime();
                        if (time > pickupEndTimestamp && LifeMemberPickupInfoState.no_written_off.equals(state)) {
                            commodityPagePresenter.setNewState(LifeMemberPickupInfoState.written_expired);
                        } else {
                            commodityPagePresenter.setNewState(state);
                        }
                    }
                });

                //用户信息
                switch (commodityPagePresenter.getCategory()) {
                    case driver:
                        if (isNotEmpty(driverList)) {
                            driverList.stream().filter(driver -> driver.getId().equals(commodityPagePresenter.getRefId())).forEach(driver -> {
                                commodityPagePresenter.setMemberName(driver.getName());
                                commodityPagePresenter.setPhone(driver.getMobileNumber());
                            });
                        }
                        break;
                    case customer:
                        if (isNotEmpty(userList)) {
                            userList.stream().filter(user -> user.getId().equals(commodityPagePresenter.getRefId())).forEach(user -> {
                                commodityPagePresenter.setMemberName(user.getName());
                                commodityPagePresenter.setPhone(user.getMobileNumber());
                            });
                        }
                }
            }
        }
        return RestResult.success(page);
    }


    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @Override
    public RestResult<OrderDetailsPresenter> details(Long id) {
        LifeMerchantMemberOrder lifeMerchantOrder = orderMapper.selectById(id);
        if (isEmpty(lifeMerchantOrder)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        OrderDetailsPresenter result =
                copyProperties(lifeMerchantOrder, OrderDetailsPresenter.class);

        if (isNotEmpty(result)) {
            Long refIds = result.getId();
            Long merchantId = result.getMerchantId();
            Long memberId = result.getMemberId();
            Long commodityId = result.getMerchantCommodityId();

            //订单ID查核销时间
            QueryWrapper<LifeMemberPickupInfo> pickupInfoWrapper = new QueryWrapper<>();
            pickupInfoWrapper.eq("ref_id", refIds);
            LifeMemberPickupInfo lifeMemberPickupInfos = lifeMemberPickupInfoMapper.selectOne(pickupInfoWrapper);
            result.setPickupInfo(lifeMemberPickupInfos);
            if (isNotEmpty(lifeMemberPickupInfos)) {
                //最晚提货时间
                Integer pickupEndTimestamp = lifeMemberPickupInfos.getPickupEndTimestamp();
                LifeMemberPickupInfoState state = lifeMemberPickupInfos.getState();
                long time = new Date().getTime() / 1000;
                if (time > pickupEndTimestamp && LifeMemberPickupInfoState.no_written_off.equals(state)) {
                    result.setNewState(LifeMemberPickupInfoState.written_expired);
                } else {
                    result.setNewState(state);
                }
            }

            //商家名称
            QueryWrapper<LifeMerchant> lifeMerchantWrapper = new QueryWrapper<>();
            lifeMerchantWrapper.select("id", "name");
            lifeMerchantWrapper.eq("id", merchantId);
            LifeMerchant lifeMerchant = lifeMerchantMapper.selectOne(lifeMerchantWrapper);
            if (isNotEmpty(lifeMerchant)) {
                result.setMerchantName(lifeMerchant.getName());
            }

            //会员信息
            QueryWrapper<LifeMember> memberWrapper = new QueryWrapper<>();
            memberWrapper.select("id", "category", "ref_id");
            memberWrapper.eq("id", memberId);
            LifeMember member = lifeMemberMapper.selectOne(memberWrapper);

            if (isNotEmpty(member)) {
                Long refId = member.getRefId();
                result.setRefId(refId);
                LifeMemberCategory category = member.getCategory();
                switch (category) {
                    case driver:
                        QueryWrapper<Driver> driverWrapper = new QueryWrapper<>();
                        driverWrapper.eq("id", refId);
                        Driver driver = driverMapper.selectOne(driverWrapper);
                        if (isNotEmpty(driver)) {
                            result.setMemberName(driver.getName());
                            result.setPhone(driver.getMobileNumber());
                        }
                        break;
                    case customer:
                        QueryWrapper<User> userWrapper = new QueryWrapper<>();
                        userWrapper.eq("id", refId);
                        User user = userMapper.selectOne(userWrapper);
                        if (isNotEmpty(user)) {
                            result.setMemberName(user.getName());
                            result.setPhone(user.getMobileNumber());
                        }
                        break;
                }
            }

            //商品信息
            QueryWrapper<LifeMerchantCommodity> commodityQueryWrapper = new QueryWrapper<>();
            commodityQueryWrapper.eq("id", commodityId);
            LifeMerchantCommodity commodity = lifeMerchantCommodityMapper.selectOne(commodityQueryWrapper);
            if (isNotEmpty(commodity)) {
                result.setLifeMerchantCommodity(commodity);
                Long commodityCategoryId = commodity.getCommodityCategoryId();
                //商品分类名称
                QueryWrapper<LifeMerchantCommodityCategory> categoryQueryWrapper = new QueryWrapper<>();
                categoryQueryWrapper.eq("id", commodityCategoryId);
                LifeMerchantCommodityCategory lifeMerchantCommodityCategory = lifeMerchantCommodityCategoryMapper.selectOne(categoryQueryWrapper);
                if (isNotEmpty(lifeMerchantCommodityCategory)) {
                    result.setCommodityCategoryName(lifeMerchantCommodityCategory.getName());
                }
            }
        }
        return RestResult.success(result);
    }

}